#include "log.h"
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include "spdlog/sinks/rotating_file_sink.h"
#include "spdlog/sinks/stdout_sinks-inl.h"

namespace {
constexpr size_t MAX_SIZE = 1024 * 1024 * 5;  // 每个日志文件大小
constexpr size_t MAX_FILES = 1;               // 最多日志文件个数

const std::map<std::string, spdlog::level::level_enum> LOG_LEVEL_MAP = {
    {"debug", spdlog::level::debug},
    {"info", spdlog::level::info},
    {"warn", spdlog::level::warn},
    {"error", spdlog::level::err},
};
}  // namespace

namespace Log {
void Init(const std::string &logName, const std::string &logPath, const std::string &logLevel)
{
    if (logLevel == "off") {
        spdlog::set_level(spdlog::level::off);
        return;
    }
    try {
        auto fileLogger = spdlog::rotating_logger_mt(logName, logPath, MAX_SIZE, MAX_FILES);
        auto it = LOG_LEVEL_MAP.find(logLevel);
        auto level = spdlog::level::info;
        if (it != LOG_LEVEL_MAP.end()) {
            level = it->second;
        }
        fileLogger->set_level(level);
        fileLogger->flush_on(level);

        const std::string pattern = "[%Y-%m-%d %H:%M:%S.%e][%n][%L][%P][%t][%s:%#]%v";
        spdlog::set_pattern(pattern);
        set_default_logger(fileLogger);
    } catch (const spdlog::spdlog_ex &ex) {
        std::cout << "Log init failed: " << ex.what() << std::endl;
    }
}
void Init(FilterConfig &config)
{
    std::stringstream logFilePath;
    logFilePath << config.GetLogPath() << "\\filter_agent.log";
    Init("filter_agent", logFilePath.str(), config.GetLogLevel());
}
}  // namespace Log